using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Unity.VisualScripting;
using UnityEngine;


public static class GameData
{
    public static int Money = 10;
    public static RoleInfo PlayerInfo = new RoleInfo();
    public static Dictionary<string, StoryInfo> StoryDic = new Dictionary<string, StoryInfo>();
    public static Dictionary<int, int> BagDic = new Dictionary<int, int>();


    public static int GetBagCount(int ItemID)
    {
        if (GameData.BagDic.ContainsKey(ItemID))
        {
            return GameData.BagDic[ItemID];
        }
        else
        {
            return 0;
        }
    }

    public static void AddItem(ItemData data)
    {
        int id = data.cfg.ID;
        int count = data.count;
        BagDic.AddOrUpdate(id, k => count, (k, v) => v += count);
    }
    public static void ReduceItem(ItemData data)
    {
        int id = data.cfg.ID;
        int curCount = GameData.GetBagCount(id);
        if (curCount < data.count)
        {
            Debug.Log("物品ID为" + id + "尝试减至负数,拒绝");
        }
        else
        {
            if (curCount == data.count)
            {
                GameData.BagDic.Remove(id);
            }
            else
            {
                BagDic.AddOrUpdate(id, k => 1, (k, v) => v -= data.count);
            }

        }
    }

    public static void ChangeMoney(this object sender, int count)
    {
        GameData.Money += count;
        EventTriggerExt.TriggerEvent(sender, (int)GameEvent.ChangMoney);
    }

    public static void ChangeLife(this object sender, int count)
    {
        GameData.PlayerInfo.Life += count;
        EventTriggerExt.TriggerEvent(sender, (int)GameEvent.ChangeLife);
    }
}

public class StoryInfo
{
    public int EventId;
    public int Influence;
}

public class RoleInfo
{
    public int PoleSex = (int)Sex.man;
    public int Level = 0;
    public int Life = 100;
    public int XiuLianRate = 1;//修炼速率
    public int SellRate = 1;//角色加成卖出倍率
    public int BuyRate = 1;//角色加成购买倍率
}

enum Sex
{
    man = 1,
    woman = 2
}

public static class DictionaryExtensions
{
    public static TValue AddOrUpdate<TKey, TValue>(
        this IDictionary<TKey, TValue> dictionary,
        TKey key,
        Func<TKey, TValue> addValueFactory,
        Func<TKey, TValue, TValue> updateValueFactory)
    {
        TValue value;
        if (dictionary.TryGetValue(key, out value))
        {
            // 键已存在，调用 updateValueFactory 更新值
            value = updateValueFactory(key, value);
            dictionary[key] = value;
        }
        else
        {
            // 键不存在，调用 addValueFactory 添加值
            value = addValueFactory(key);
            dictionary[key] = value;
        }

        return value;
    }
}